// time_utils.cpp
// pruebas de tiempo para entrega 2
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sys/timeb.h>
#include <sqlite3.h>
#include "time_utils.h"

using namespace std;
namespace TimeUtils{
  // This is the callback function to display the select data in the table
  int TestCapacityUtils::callback(void *NotUsed, int argc, char **argv, char **szColName){
    for(int i = 0; i < argc; i++){
      cout << szColName[i] << " = " << argv[i] << std::endl;
    }
    cout << "\n";
    return 0;
  }

  void TestCapacityUtils::Test_Capacity(){
    sqlite3 *db;
    char *szErrMsg = 0;
    // open database
    int rc = sqlite3_open("data_file.db", &db);
    if(rc){
      cout << "Can't open database\n";
    } else {
      cout << "Open database successfully\n";
    }

    rc = sqlite3_exec(db, "drop table if exists nodes;", callback, 0, &szErrMsg);
    rc = sqlite3_exec(db,
		      """CREATE TABLE nodes(              \
                              iden integer primary key, \
                              coX integer,              \
                              coY integer,              \
                              cost integer,             \
                              prof integer,             \
                              father integer,           \
                              f integer);""",
		      callback, 0, &szErrMsg);

    char aux_chars[100]; // enough to hold all numbers up to 64-bits
    int j, cost;

    struct timeb startT, finishT;
    unsigned int seconds, milliseconds;
    ftime(&startT);

    for(j=1; j<1000001; j++){
      cost = rand() % 1000;
      sprintf(aux_chars, "INSERT INTO nodes VALUES(%d, 0, 0, %d, %d, %d, 8)", j, cost, j-1, j-1);
      rc = sqlite3_exec(db, aux_chars, callback, 0, &szErrMsg);
    }
    if(rc != SQLITE_OK){
      cout << "SQL Error: " << szErrMsg << std::endl;
      sqlite3_free(szErrMsg);
    }

    // close database
    if(db) {
      sqlite3_close(db);
    }

    ftime(&finishT);
    seconds = finishT.time - startT.time - 1;
    milliseconds = (1000 - startT.millitm) + finishT.millitm;
    cout<< "Tiempo inseción 1000000 elementos: " << seconds << "." << milliseconds << " seg" << endl;

  }

}
